//
//  EmoticonView.swift
//  模拟键盘
//
//  Created by apple on 15/12/15.
//  Copyright © 2015年 idcast. All rights reserved.
//

import UIKit
//可重用的cell
private let EmoticonViewCellId = "EmoticonViewCellId"
///表情键盘视图
class EmoticonView: UIView {
    ///选中表情回调
    private var selectedEmoticonCallBack: (emotion: Emoticon) -> ()
    
    ///MARK： 监听方法
    @objc private func clickItem(item: UIBarButtonItem){
        
        print("选中的\(item.tag)")
        
        let indexPath = NSIndexPath(forItem: 0, inSection: item.tag)
        //滚动collectionView
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: true)
    }
    
    
    //MARK: 构造函数  自定构造函数
    init(selectedEmoticon: (emoticon: Emoticon)->()) {
    
        //记录闭包的属性
        selectedEmoticonCallBack = selectedEmoticon
        
        //调用父类的构造函数
        var rect = UIScreen.mainScreen().bounds
        rect.size.height = 216
        super.init(frame: rect)
        backgroundColor = UIColor.redColor()
        setupUI()
        
        //滚动到第一页
        let indexPath = NSIndexPath(forItem: 0, inSection: 1)
        // 主队列的的异步  其余的东西都加载完成后 在执行滚动的方法
        dispatch_async(dispatch_get_main_queue()) { () -> Void in
            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
        }
        
    }
//    override init(frame: CGRect) {
//        var rect = UIScreen.mainScreen().bounds
//        rect.size.height = 216
//        super.init(frame: rect)
//        backgroundColor = UIColor.redColor()
//        setupUI()
//        
//        //滚动到第一页 
//        let indexPath = NSIndexPath(forItem: 0, inSection: 1)
//        // 主队列的的异步  其余的东西都加载完成后 在执行滚动的方法
//        dispatch_async(dispatch_get_main_queue()) { () -> Void in
//            self.collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: .Left, animated: false)
//        }
//        
//    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 懒加载控件
    private lazy var collectionView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticontLayout())
    
    private lazy var toolbar = UIToolbar()
    //表情包数组
    private lazy var packages = EmoticonManger.sharedManger.packages
    //MARK 表情布局
    private class EmoticontLayout: UICollectionViewFlowLayout {
        private override func prepareLayout() {
            super.prepareLayout()
            
            let col: CGFloat = 7
            let row: CGFloat = 3
            let w = (collectionView?.bounds.width)! / col
            let margin = ((collectionView?.bounds.height)! - row * w ) * 0.499
            
            itemSize = CGSize(width: w, height: w)
            minimumInteritemSpacing = 0
            minimumLineSpacing = 0
            sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
            
            scrollDirection = .Horizontal
            collectionView?.pagingEnabled = true
            collectionView?.bounces = false
            collectionView?.showsHorizontalScrollIndicator = false
            
        }
        
    }
}
//MARK: 设置界面
private extension EmoticonView {
    
    func setupUI() {
        //0 设置颜色 tintcolor
        toolbar.tintColor = UIColor.darkGrayColor()
        //1 添加控件
        addSubview(toolbar)
        addSubview(collectionView)
        
        //2 自动布局
        toolbar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self.snp_bottom)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
            make.height.equalTo(36)
        }
        collectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_top)
            make.bottom.equalTo(toolbar.snp_top)
            make.left.equalTo(self.snp_left)
            make.right.equalTo(self.snp_right)
        }
        
        //准备控件
        prepareToolbar()
        prepareCollectionView()
    }
    ///准备工具栏
    private func prepareToolbar() {
        
        //1 设置按钮的内容
        var items = [UIBarButtonItem]()
        
        var index = 0
        for p in packages {
            
            items.append(UIBarButtonItem(title: p.group_name_cn, style: .Plain, target: self , action: "clickItem:"))
            items.last?.tag = index++
            
            //添加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
            
        }
        //取消最后一个
        items.removeLast()
        
        //2 设置items
        toolbar.items = items
    }
    ///准备collectionView
    private func prepareCollectionView() {
        
        collectionView.backgroundColor = UIColor.lightGrayColor()
        //注册cell
        collectionView.registerClass(EmotionViwCell.self, forCellWithReuseIdentifier: EmoticonViewCellId)
        //设置数据源
        collectionView.dataSource = self
        //设置代理
        collectionView.delegate = self
    }
}
///MARK: 数据源的方法

extension EmoticonView: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //获取表情模型
        let em = packages[indexPath.section].emoticons[indexPath.item]
        
        //执行回调
        selectedEmoticonCallBack(emotion: em)
    }
    
    //返回分组数量 表情包的数量
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticons.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonViewCellId, forIndexPath: indexPath) as! EmotionViwCell
   
        cell.backgroundColor = indexPath.item % 2 == 0 ? UIColor.redColor() : UIColor.greenColor()
        
//        cell.emotionButton.setTitle("\(indexPath.item)", forState: .Normal)
        cell.emoticon = packages[indexPath.section].emoticons[indexPath.item]
        
        return cell
    }
}
//MARK: 表情cell
private class EmotionViwCell: UICollectionViewCell {
    //表情模型
    var emoticon: Emoticon? {
    
        didSet{
        
            emotionButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: .Normal)
            
            emotionButton.setTitle(emoticon?.emoji, forState: .Normal)
            //设置删除按钮
            if emoticon!.isRemoved {
            
                emotionButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
            }
            

        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(emotionButton)
        emotionButton.backgroundColor = UIColor.whiteColor()
        emotionButton.setTitleColor(UIColor.redColor(), forState: .Normal)
        emotionButton.frame = CGRectInset(bounds, 4, 4)
        
        emotionButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        
        //取消交互
        emotionButton.userInteractionEnabled = false
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //懒加载控件
    private lazy var emotionButton: UIButton = UIButton()
}



